# -*- coding: utf-8 -*-

from ldap3 import Server, Connection, ALL, SUBTREE, ServerPool
import base64
import hashlib

LDAP_SERVER_POOL = ["10.39.95.5",]
LDAP_SERVER_PORT = 389
ADMIN_DN = "administrator"
ADMIN_PASSWORD = "Qdingnet@2018"
SEARCH_BASE = "ou=千丁互联,dc=qdingnet,dc=cn"


def ldap_auth():
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool,user=ADMIN_DN,password=ADMIN_PASSWORD, check_names=True, lazy=False, raise_exceptions=False)
    conn.open()
    conn.bind()
    # conn.result
    res = conn.search(
        search_base = SEARCH_BASE,
        search_filter = '(sAMAccountName=chenyugang)',
        search_scope = SUBTREE,
        attributes = ['cn','userPassword'],
    )
    print(res)
    #
    if res:
        entry = conn.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']
        print("aa",entry)
        print("bb",dn)
        print("cc",attr_dict)
        password="123456"

    #
    #     # check password by dn

        try:
            conn2 = Connection(ldap_server_pool, user=dn, password=ADMIN_PASSWORD, check_names=True, lazy=False, raise_exceptions=False)
            conn2.bind()
            print(conn2.result)
    #         if conn2.result["description"] == "success":
    #             print((True, attr_dict["mail"], attr_dict["sAMAccountName"], attr_dict["givenName"]))
    #             return (True, attr_dict["mail"], attr_dict["sAMAccountName"], attr_dict["givenName"])
    #         else:
    #             print("auth fail")
    #             return (False, None, None, None)
        except Exception as e:
            print("auth fail")
            return (False, None, None, None)
    # else:
    #     return (False, None, None, None)

def hash_md5(data):
     md = hashlib.md5()
     md.update(data.encode("utf8"))
     a = md.digest()
     b = '{MD5}' + str(base64.b64encode(a))
     print("bbb",b)
     return b

if __name__ == "__main__":
    ldap_auth()
